package com.wei.tang;

import com.wei.tang.R;
import com.wei.tang.bean.UserBean;
import com.wei.tang.db.UserDao;
import com.wei.tang.ui.MainActivity;
import com.wei.tang.util.Tlog;
import com.wei.tang.util.Util;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.view.View;
import android.view.animation.AlphaAnimation;
import android.view.animation.Animation;
import android.view.animation.Animation.AnimationListener;

public class AppStart extends Activity {

	private AppStart mySelf = this;

	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		// 防止第三方跳转时出现双实例
		Activity aty = AppManager.getActivity(MainActivity.class);
		if (aty != null && !aty.isFinishing()) {
			finish();
		}

		final View view = View.inflate(this, R.layout.app_start, null);
		setContentView(view);
		// 渐变展示启动屏
		AlphaAnimation aa = new AlphaAnimation(0.5f, 1.0f);
		aa.setDuration(1000);
		view.startAnimation(aa);
		aa.setAnimationListener(new AnimationListener() {
			@Override
			public void onAnimationEnd(Animation arg0) {
				redirectTo();
			}

			@Override
			public void onAnimationRepeat(Animation animation) {
			}

			@Override
			public void onAnimationStart(Animation animation) {
				autoLogin();
			}
		});
	}

	/**
	 * 自动登录
	 */
	private void autoLogin() {
		String userSession = AppContext.getInstance().getProperty("user.session");
		// SharedPreferences preferences = getSharedPreferences("weiketang",
		// Context.MODE_PRIVATE);
		Tlog.i("userSession:" + userSession);
		if (userSession != null && !userSession.equals("")) {
			UserDao userDao = new UserDao(mySelf);
			UserBean userBean = userDao.findUserByUserSession(userSession);
			if (userBean != null) {
				AppContext.getInstance().userLogin(userBean);
				Tlog.i("自动登录成功");
			} else {
				AppContext.getInstance().setProperty("user.phone", "");
			}
		}
	}

	/**
	 * App启动之后的跳转，如果是第一次安装就跳转到指导页面，不是第一次就跳到主页
	 */
	private void redirectTo() {
		Intent intent = null;
		if (Util.isFirstTimeStart(mySelf)) {
			intent = new Intent(mySelf, AppGuideActivity.class);
		} else {
			intent = new Intent(mySelf, MainActivity.class);
		}
		startActivity(intent);
		mySelf.finish();
	}
}
